package com.czq.controllor;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.czq.common.Result;
import com.czq.execption.BusinessEXception;
import com.czq.pojo.CateGory;
import com.czq.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryControllor {
    @Autowired
    private CategoryService categoryService;

    @PostMapping
    public Result<String> save(@RequestBody CateGory cateGory) {
        log.info("数据是：{}", cateGory);

        try {
            categoryService.save(cateGory);
        } catch (Exception ex) {

            throw new BusinessEXception("菜品名重复，添加失败");
        }

        return Result.success("添加成功");
    }

    @GetMapping("/page")
    public Result<Page> getPage(@RequestParam("page") Integer page, @RequestParam("pageSize") Integer pageSize) {
        Page p = new Page(page, pageSize);
        LambdaQueryWrapper<CateGory> queryWrapper = new LambdaQueryWrapper<CateGory>();
        queryWrapper.orderByAsc(CateGory::getSort);
        categoryService.page(p, queryWrapper);


        return Result.success(p);
    }

    @DeleteMapping
    public Result<String> delete(@RequestParam("ids") Long ids) {
        categoryService.deleteByid(ids);
        return Result.success("删除成功");

    }

    @PutMapping
    public Result<String> update(@RequestBody CateGory cateGory) {
        categoryService.updateById(cateGory);
        return Result.success("修改成功");

    }

    @GetMapping("/list")
    public Result<List<CateGory>> list(Integer type) {

//
//        LambdaQueryWrapper<CateGory> queryWrapper2 = new LambdaQueryWrapper<CateGory>();
//
//        queryWrapper2.eq(CateGory::getType, type);
//        List<CateGory> list22 = categoryService.list(queryWrapper2);
//        return Result.success(list);


        //条件构造器
        LambdaQueryWrapper<CateGory> queryWrapper = new LambdaQueryWrapper<>();
        //添加条件

        queryWrapper.eq(type!=null,CateGory::getType,type);
        //添加排序条件
        queryWrapper.orderByAsc(CateGory::getSort).orderByDesc(CateGory::getUpdateTime);

        List<CateGory> list = categoryService.list(queryWrapper);
        return Result.success(list);

    }

}


